<template>
  <div class="home-container layout-pd">
    <el-row :gutter="15" class="home-count-box mb15">
      <el-col :span="6">
        <div
          class="home-count-item bg-color-primary"
          @click="openPath('/orderManage/order', { status: '待支付' })"
        >
          <el-statistic
            :value="waitItemCount.pendingPaymentCount"
            value-style="font-size: 35px;text-align: center;color: white"
          >
            <template #title>
              <div class="item-count-title">待支付</div>
            </template>
          </el-statistic>
        </div>
      </el-col>
      <el-col :span="6">
        <div
          class="home-count-item bg-color-success"
          @click="openPath('/orderManage/order', { status: '待发货' })"
        >
          <el-statistic
            :value="waitItemCount.pendingShipmentCount"
            value-style="font-size: 35px;text-align: center;color: white"
          >
            <template #title>
              <div class="item-count-title">待发货</div>
            </template>
          </el-statistic>
        </div>
      </el-col>
      <el-col :span="6">
        <div
          class="home-count-item bg-color-warning"
          @click="openPath('/orderManage/billAftersales')"
        >
          <el-statistic
            :value="waitItemCount.pendingAftersalesCount"
            value-style="font-size: 35px;text-align: center;color: white"
          >
            <template #title>
              <div class="item-count-title">待售后</div>
            </template>
          </el-statistic>
        </div>
      </el-col>
      <el-col :span="6">
        <div
          class="home-count-item bg-color-danger"
          @click="openPath('/good/goods', { activeGood: '库存报警' })"
        >
          <el-statistic
            :value="waitItemCount.stockWarnCount"
            value-style="font-size: 35px;text-align: center;color: white"
          >
            <template #title>
              <div class="item-count-title">库存报警</div>
            </template>
          </el-statistic>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="15" class="home-card-box mb15">
      <el-col :span="10">
        <div class="home-nav-item">
          <div class="item-title">快捷方式</div>
          <el-row :gutter="15" class="mb15">
            <el-col :span="6" @click="openPath('/good/goods')"
              ><div class="nav-item-menu">
                <div class="menu-icon">
                  <i class="iconfont icon-shangpinguanli"></i>
                </div>
                <div class="menu-name">商品</div>
              </div></el-col
            >
            <el-col :span="6" @click="openPath('/orderManage/order')"
              ><div class="nav-item-menu">
                <div class="menu-icon">
                  <el-icon :size="28" color="#606266">
                    <ShoppingTrolley />
                  </el-icon>
                </div>
                <div class="menu-name">订单</div>
              </div></el-col
            >
            <el-col :span="6" @click="openPath('/member/sysUser')"
              ><div class="nav-item-menu">
                <div class="menu-icon">
                  <i class="iconfont icon-Member"></i>
                </div>
                <div class="menu-name">会员</div>
              </div></el-col
            >
            <el-col :span="6" @click="openPath('/operationManage/notices')"
              ><div class="nav-item-menu">
                <div class="menu-icon">
                  <i class="iconfont icon-gonggao"></i>
                </div>
                <div class="menu-name">公告</div>
              </div></el-col
            >
          </el-row>
          <el-row :gutter="15" class="mb15">
            <el-col :span="6" @click="openPath('/promotion/coupon')"
              ><div class="nav-item-menu">
                <div class="menu-icon">
                  <i class="iconfont icon-youhuijuan"></i>
                </div>
                <div class="menu-name">优惠劵</div>
              </div></el-col
            >
            <el-col :span="6" @click="openPath('/shopSetting/ships')"
              ><div class="nav-item-menu">
                <div class="menu-icon">
                  <i class="iconfont icon-wuliu"></i>
                </div>
                <div class="menu-name">配送</div>
              </div></el-col
            >
            <el-col :span="6" @click="openPath('/promotion/groupSeckill')"
              ><div class="nav-item-menu">
                <div class="menu-icon">
                  <i class="iconfont icon-yingxiaogongju-tuangoumiaosha1"></i>
                </div>
                <div class="menu-name">商品秒杀</div>
              </div></el-col
            >
            <el-col :span="6" @click="openPath('/shopSetting/platform')"
              ><div class="nav-item-menu">
                <div class="menu-icon">
                  <i class="iconfont icon-pingtaishezhi"></i>
                </div>
                <div class="menu-name">平台设置</div>
              </div></el-col
            >
          </el-row>
          <el-row :gutter="15" class="mb15">
            <el-col :span="6" @click="openPath('/financialManage/billPayment')"
              ><div class="nav-item-menu">
                <div class="menu-icon">
                  <i class="iconfont icon-zhifudanju"></i>
                </div>
                <div class="menu-name">支付单</div>
              </div></el-col
            >
            <el-col :span="6" @click="openPath('/orderManage/billDelivery')"
              ><div class="nav-item-menu">
                <div class="menu-icon">
                  <el-icon :size="28" color="#606266">
                    <Van />
                  </el-icon>
                </div>
                <div class="menu-name">发货单</div>
              </div></el-col
            >
            <el-col :span="6" @click="openPath('/shopSetting/pageDesign')"
              ><div class="nav-item-menu">
                <div class="menu-icon">
                  <i class="iconfont icon-webyemiansheji"></i>
                </div>
                <div class="menu-name">页面设计</div>
              </div></el-col
            >
            <el-col :span="6" @click="openPath('/shopSetting/store')"
              ><div class="nav-item-menu">
                <div class="menu-icon">
                  <i class="iconfont icon-8"></i>
                </div>
                <div class="menu-name">门店管理</div>
              </div></el-col
            >
          </el-row>
        </div>
      </el-col>
      <el-col :span="14">
        <div class="home-order-item">
          <div class="item-title">本周订单销售金额</div>
          <el-row :gutter="15">
            <el-col :span="24">
              <div class="order-week-item">
                <div class="bar-chart-container" ref="orderWeekOrderBarChartRef"></div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="15" class="home-card-box mb15">
      <el-col :span="10">
        <div class="home-order-item">
          <div class="item-title">销售订单状态</div>
          <el-row :gutter="15" class="mb15">
            <el-col :span="24">
              <div class="order-status-item">
                <div class="pie-chart-container" ref="orderStatusPieChartRef"></div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-col>
      <el-col :span="14">
        <div class="home-login-item">
          <div class="item-title">最近登录</div>
          <el-table :data="state.securityLogData" style="width: 100%">
            <el-table-column fixed type="index" label="序号" width="60" />
            <el-table-column
              prop="userName"
              label="操作人"
              width="100"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="applicationName"
              label="应用程序"
              width="150"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="identity"
              width="120"
              label="用户身份"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              prop="action"
              label="执行操作"
              width="150"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="clientIpAddress"
              label="客户端IP"
              width="150"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="clientId"
              label="ClientId"
              width="180"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="browserInfo"
              label="浏览器"
              width="200"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              fixed="right"
              prop="creationTime"
              label="创建日期"
              width="170"
              show-overflow-tooltip
            >
              <template #default="scope">
                <span>{{ scope.row.creationTime }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts" name="home">
import {
  reactive,
  onBeforeMount,
  onMounted,
  ref,
  watch,
  nextTick,
  onActivated,
  markRaw,
} from "vue";
import { Van, ShoppingTrolley } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import * as echarts from "echarts";
import { storeToRefs } from "pinia";
import { useThemeConfig } from "/@/stores/themeConfig";
import { useTagsViewRoutes } from "/@/stores/tagsViewRoutes";
import { useHomeApi } from "/@/api/home/index";
import { useOrderApi } from "/@/api/orderManage/order/index";
import { useSecurityLogApi } from "/@/api/logManage/securityLog/index";

// 定义变量内容
const router = useRouter();
const orderWeekOrderBarChartRef = ref();
const orderStatusPieChartRef = ref();
const storesTagsViewRoutes = useTagsViewRoutes();
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const { isTagsViewCurrenFull } = storeToRefs(storesTagsViewRoutes);
const waitItemCount = ref<WaitItemCountType>({
  pendingPaymentCount: 0,
  pendingShipmentCount: 0,
  pendingAftersalesCount: 0,
  stockWarnCount: 0,
});
const state = reactive({
  global: {
    weekOrderAmountChart: null,
    orderStatusChart: null,
    dispose: [null, "", undefined],
  } as any,
  myCharts: [] as EmptyArrayType,
  charts: {
    theme: "",
    bgColor: "",
    color: "#303133",
  },
  securityLogData: [] as RowSecurityLogType[],
});

// 功能跳转
const openPath = (path: string, param = {}) => {
  const params: EmptyObjectType = param;
  router.push({
    path,
    query: params,
  });
};

// 销售订单状态统计
const initOrderStatusChart = (legendData: string[], seriesData: any) => {
  if (!state.global.dispose.some((b: any) => b === state.global.orderStatusChart))
    state.global.orderStatusChart.dispose();
  state.global.orderStatusChart = markRaw(
    echarts.init(orderStatusPieChartRef.value, state.charts.theme)
  );
  const colorList = [
    /* "#51A3FC", "#FEC279", */
    "#e6a23c",
    "#968AF5",
    "#E790E8",
    "#36C78B",
  ];
  const option = {
    backgroundColor: state.charts.bgColor,
    tooltip: {
      trigger: "item",
      formatter: (obj: any) => {
        return `${obj.name}<br />数量：${obj.value}<br />占比：${obj.percent}%`;
      },
    },
    graphic: {
      elements: [
        {
          type: "image",
          z: -1,
          style: {
            image: themeConfig.value.isIsDark
              ? ""
              : "",
            width: 230,
            height: 230,
          },
          left: "16.5%",
          top: "center",
        },
      ],
    },
    legend: {
      type: "scroll",
      orient: "vertical",
      right: "0%",
      left: "65%",
      top: "center",
      itemWidth: 14,
      itemHeight: 14,
      data: legendData,
      textStyle: {
        rich: {
          name: {
            fontSize: 16,
            fontWeight: 400,
            width: 200,
            height: 35,
            padding: [0, 0, 0, 60],
            color: state.charts.color,
          },
          rate: {
            fontSize: 15,
            fontWeight: 500,
            height: 35,
            width: 40,
            padding: [0, 0, 0, 30],
            color: state.charts.color,
          },
        },
      },
    },
    series: [
      {
        type: "pie",
        radius: ["82", themeConfig.value.isIsDark ? "50" : "102"],
        center: ["32%", "50%"],
        itemStyle: {
          color: function (params: any) {
            return colorList[params.dataIndex];
          },
        },
        label: { show: false },
        labelLine: { show: false },
        data: seriesData,
      },
    ],
  };
  state.global.orderStatusChart.setOption(option);
  state.myCharts.push(state.global.orderStatusChart);
};

// 批量设置 echarts resize
const initEchartsResizeFun = () => {
  nextTick(() => {
    for (let i = 0; i < state.myCharts.length; i++) {
      setTimeout(() => {
        state.myCharts[i].resize();
      }, i * 1000);
    }
  });
};

// 批量设置 echarts resize
const initEchartsResize = () => {
  window.addEventListener("resize", initEchartsResizeFun);
};

// 获取待办事项数量
const getWaitItemCount = () => {
  useHomeApi()
    .getWaitItemCount()
    .then((result) => {
      if (!result) return;
      waitItemCount.value = result;
    })
    .catch((err) => {
      console.error("查询待办事项数量出错：", err);
    });
};

// 查询订单数量
const getStatusQuantity = () => {
  useOrderApi()
    .getStatusQuantity()
    .then((result) => {
      if (!result) return;
      let pieData = new Array();
      /*
      pieData.push({
        name: "待支付",
        value: result.pendingPayment,
      });
      pieData.push({
        name: "待发货",
        value: result.pendingShipment,
      });
      */
      pieData.push({
        name: "待收货",
        value: result.pendingDelivery,
      });
      pieData.push({
        name: "待评价",
        value: result.pendingEvaluate,
      });
      pieData.push({
        name: "已取消",
        value: result.cancelled,
      });
      pieData.push({
        name: "已完成",
        value: result.completed,
      });
      let legendData = pieData.map((x) => x.name);
      initOrderStatusChart(legendData, pieData);
    })
    .catch((err: any) => {
      console.error("查询订单数量出错：", err);
    });
};

// 获取本周订单销售总额
const getWeekOrderAmountStatistics = () => {
  useHomeApi()
    .getWeekOrderAmountStatistics()
    .then((result) => {
      if (!result) return;
      let xAxisData = new Array<string>();
      let legendData = new Array<string>();
      let seriesData = {} as any;
      for (let key in result) {
        let datas = result[key];
        seriesData[key] = [];
        legendData.push(key);
        for (let i = 0; i < datas.length; i++) {
          const data = datas[i];
          let date = data.orderDate.substring(0, 10);
          if (!xAxisData.includes(date)) {
            xAxisData.push(date);
          }
          seriesData[key].push(data.totalAmount);
        }
      }
      initWeekOrderAmountChart(legendData, xAxisData, seriesData);
    })
    .catch((err) => {
      console.error("查询本周订单销售总额出错：", err);
    });
};

// 初始化[本周订单销售总额]图表
const initWeekOrderAmountChart = (
  legendData: string[],
  xAxisData: string[],
  seriesData: any
) => {
  if (!state.global.dispose.some((b: any) => b === state.global.weekOrderAmountChart))
    state.global.weekOrderAmountChart.dispose();
  state.global.weekOrderAmountChart = markRaw(
    echarts.init(orderWeekOrderBarChartRef.value, state.charts.theme)
  );

  const option = {
    backgroundColor: state.charts.bgColor,
    grid: {
      top: "5%",
      right: 0,
      bottom: "10%",
      // left: "5%",
    },
    tooltip: { trigger: "axis" },
    legend: {
      data: legendData,
    },
    xAxis: {
      data: xAxisData,
    },
    yAxis: [
      {
        type: "value",
        name: "金额(元)",
        splitLine: {
          show: true,
          lineStyle: {
            type: "dashed",
            color: "#f5f5f5",
          },
        },
      },
    ],
    series: [
      {
        name: "全部",
        type: "bar",
        barWidth: 30,
        itemStyle: {
          color: "#409eff",
          borderColor: "#409eff",
          borderRadius: [30, 30, 0, 0],
        },
        data: seriesData["全部"],
      },
      {
        name: "待付款",
        type: "line",
        symbolSize: 6,
        symbol: "circle",
        smooth: true,
        data: seriesData["待付款"],
        lineStyle: { color: "#e6a23c" },
        itemStyle: { color: "#e6a23c", borderColor: "#e6a23c" },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#e6a23cb3" },
            { offset: 1, color: "#e6a23c03" },
          ]),
        },
      },
      {
        name: "已付款",
        type: "line",
        symbolSize: 6,
        symbol: "circle",
        smooth: true,
        data: seriesData["已付款"],
        lineStyle: { color: "#18bdab" },
        itemStyle: { color: "#18bdab", borderColor: "#18bdab" },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#18bdabb3" },
            { offset: 1, color: "#18bdab03" },
          ]),
        },
      },
    ],
  };

  state.global.weekOrderAmountChart.setOption(option);
  state.myCharts.push(state.global.weekOrderAmountChart);
};

// 获取最近登录日志信息
const getSecurityLog = () => {
  useSecurityLogApi()
    .getSecurityLogList({
      actionName: "",
      userName: "",
      sorting: "creationTime desc",
      skipCount: 0,
      maxResultCount: 5,
    })
    .then((result) => {
      state.securityLogData = result.items;
    })
    .catch((err: any) => {
      console.error("查询安全日志列表出错：", err);
    });
};

// 页面加载前
onBeforeMount(() => {
  getWaitItemCount();
  // 查询最近登录日志信息
  getSecurityLog();
});

// 页面加载完时
onMounted(() => {
  initEchartsResize();
});

// 由于页面缓存原因，keep-alive
onActivated(() => {
  // 查询待办事项数量
  getWaitItemCount();

  // 图表大小重置
  initEchartsResizeFun();
});

// 监听 pinia 中的 tagsview 开启全屏变化，重新 resize 图表，防止不出现/大小不变等
watch(
  () => isTagsViewCurrenFull.value,
  () => {
    initEchartsResizeFun();
  }
);

// 监听 pinia 中是否开启深色主题
watch(
  () => themeConfig.value.isIsDark,
  (isIsDark) => {
    nextTick(() => {
      state.charts.theme = isIsDark ? "dark" : "";
      state.charts.bgColor = isIsDark ? "transparent" : "";
      state.charts.color = isIsDark ? "#dadada" : "#303133";
      setTimeout(() => {
        getStatusQuantity();
      }, 500);
      setTimeout(() => {
        getWeekOrderAmountStatistics();
      }, 700);
    });
  },
  {
    deep: true,
    immediate: true,
  }
);
</script>

<style scoped lang="scss">
$homeNavLengh: 8;
.home-container {
  overflow: hidden;

  .home-count-box {
    text-align: center;
    .home-count-item {
      position: relative;
      background-color: white;
      padding: 15px;
      border-radius: 5px;
      .item-count-title {
        margin-top: 5px;
        margin-bottom: 20px;
        width: 100%;
        text-align: center;
        font-size: 16px;
        color: white;
      }
      cursor: pointer;
    }
    .home-count-item::before {
      content: "";
      position: absolute;
      width: 80%;
      height: 100px;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 50%;
      left: -80px;
      bottom: -70px;
    }
    .home-count-item::after {
      content: "";
      position: absolute;
      width: 70%;
      height: 125px;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 56%;
      bottom: -80px;
      right: -80px;
    }
    .bg-color-primary {
      background-color: #409eff;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      transition: transform 0.3s, box-shadow 0.3s;
    }
    .bg-color-success {
      background-color: #18bdab;
    }
    .bg-color-warning {
      background-color: #e6a23c;
    }
    .bg-color-danger {
      background-color: #ee6666;
    }
  }

  .home-card-box {
    .home-nav-item {
      background-color: white;
      border-radius: 5px;
      padding: 15px;
      height: 340px;
      .item-title {
        font-size: 16px;
        font-weight: bold;
        height: 30px;
      }
      .nav-item-menu {
        width: 100%;
        border-radius: 5px;
        background-color: #f8f8f8;
        cursor: pointer;
        .menu-icon {
          text-align: center;
          padding-top: 15px;
          .iconfont {
            font-size: 28px;
            color: #606266;
          }
        }
        .menu-name {
          text-align: center;
          font-size: 14px;
          padding: 10px 0px;
        }
      }
      .nav-item-menu:hover {
        background-color: #edf5fe !important;
      }
    }
  }

  .home-order-item,
  .home-login-item {
    background-color: white;
    border-radius: 5px;
    padding: 15px;
    height: 340px;
    .item-title {
      font-size: 16px;
      font-weight: bold;
      height: 30px;
    }
    .order-week-item {
      width: 100%;
      .bar-chart-container {
        height: 290px;
      }
    }
    .order-status-item {
      width: 100%;
      .pie-chart-container {
        height: 280px;
      }
    }
  }
}
</style>
